//
//  WmcUploadFailureVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/1.
//

import Foundation

// MARK: - 扩展WmcUploadFailureVC + WmcNavigatorProtocol

extension WmcUploadFailureVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.uploadFailure]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vc = WmcUploadFailureVC()
        return vc
    }
}

// MARK: - [WmcUploadFailureVC]

class WmcUploadFailureVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "同步列表"
        setupUI()
        makeConstraints()
        bindEvent()

        viewModel.query { [weak self] value in
            guard let weakSelf = self else { return }

            if weakSelf.viewModel.dataSource.count == 0 {
                weakSelf.tipView.isHidden = false
            } else {
                if value.uploadingCount > 0 {
                    weakSelf.statusLabel.text = "正在同步（\(value.uploadingCount)）..."
                    weakSelf.retryBtn.isHidden = true
                } else {
                    weakSelf.statusLabel.text = "同步失败（\(value.totalCount)）"
                    weakSelf.retryBtn.isHidden = false
                }
            }

            weakSelf.listTableView.reloadData()
        }
    }

    deinit {}

    // Private

    private var headerView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_blue_DFE9FA
        return view
    }()

    private var warningImageView: UIImageView = {
        let view = UIImageView(image: "upload_failure_notice".wmc_image)
        return view
    }()

    private var statusLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_mainTheme
        label.font = 14.wmc_font
        return label
    }()

    private var retryBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("全部重试", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.layer.cornerRadius = 4.0
        btn.backgroundColor = .wmc_mainTheme
        return btn
    }()

    private var viewModel: WmcUploadFailureVM = {
        let vm = WmcUploadFailureVM()
        return vm
    }()

    private lazy var listTableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.register(WmcUploadFailureCell.self, forCellReuseIdentifier: "WmcUploadFailureCell")
        return view
    }()

    private lazy var tipView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        view.isHidden = true

        let imageView = UIImageView(image: "uploading_success".wmc_image)
        view.addSubview(imageView)

        let label = UILabel()
        label.text = "所有照片都已同步成功"
        label.font = .systemFont(ofSize: 16)
        label.textColor = .wmc_grayH2_323233
        view.addSubview(label)

        imageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(100)
            make.width.height.equalTo(80)
        }

        label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(imageView.snp.bottom).offset(21)
        }

        return view
    }()

    private func setupUI() {
        makeNavView(showShadow: false)

        view.backgroundColor = .wmc_grayH20_F7F7F7
        addSubview(headerView)
        headerView.addSubview(warningImageView)
        headerView.addSubview(statusLabel)
        headerView.addSubview(retryBtn)
        addSubview(listTableView)
        addSubview(tipView)
    }

    private func makeConstraints() {
        headerView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        }

        warningImageView.snp.makeConstraints { make in
            make.left.equalTo(13)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }

        statusLabel.snp.makeConstraints { make in
            make.left.equalTo(warningImageView.snp.right).offset(6)
            make.centerY.equalToSuperview()
        }

        retryBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.width.equalTo(56)
            make.height.equalTo(24)
            make.centerY.equalToSuperview()
        }

        listTableView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(8)
            make.left.right.bottom.equalToSuperview()
        }

        tipView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.bottom.left.right.equalToSuperview()
        }
    }

    private func bindEvent() {
        WmcUploadQueueManager.shared.startAutoUploadSubject.subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            for (_, item) in weakSelf.viewModel.dataSource.enumerated() {
                if !item.uploading {
                    item.uploading = true
                }
            }
            weakSelf.listTableView.reloadData()
            weakSelf.statusLabel.text = "正在同步（\(weakSelf.viewModel.dataSource.count)）..."
            weakSelf.hiddenWarningImageView(true)
            weakSelf.retryBtn.isHidden = true
        }.disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.taskUploadSuccessSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            var index = -1
            var uploadingCount = -1
            for (i, item) in weakSelf.viewModel.dataSource.enumerated() {
                if item.uuid == model.uuid {
                    index = i
                }
                if item.uploading {
                    uploadingCount += 1
                }
            }
            if index < weakSelf.viewModel.dataSource.count && index >= 0 {
                weakSelf.viewModel.dataSource.remove(at: index)
            }
            weakSelf.listTableView.reloadData()
            if uploadingCount > 0 {
                weakSelf.statusLabel.text = "正在同步（\(uploadingCount)）..."
                weakSelf.hiddenWarningImageView(true)
            }
        }).disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.completionSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            if weakSelf.viewModel.dataSource.count > 0 {
                weakSelf.statusLabel.text = "同步失败（\(weakSelf.viewModel.dataSource.count)）"
                weakSelf.hiddenWarningImageView(false)
                weakSelf.retryBtn.isHidden = false
            } else {
                weakSelf.tipView.isHidden = false
            }
        }).disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.failureSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            if weakSelf.viewModel.dataSource.count > 0 {
                weakSelf.statusLabel.text = "同步失败（\(weakSelf.viewModel.dataSource.count)）"
                weakSelf.hiddenWarningImageView(false)
                weakSelf.retryBtn.isHidden = false
                for (_, item) in weakSelf.viewModel.dataSource.enumerated() {
                    item.uploading = false
                }
                weakSelf.listTableView.reloadData()
            }
        }).disposed(by: rx.disposeBag)

        retryBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _Arg in
            guard let weakSelf = self else { return }
            let networkType = YPNetworkReachability.queryNetworkReachabilityType()
            if networkType == .unknow || networkType == .notReachable {
                WmcHudManager.toast("网络不佳，请稍后再试")
                return
            }

            for (_, item) in weakSelf.viewModel.dataSource.enumerated() {
                if !item.uploading {
                    item.uploading = true
                    WmcUploadQueueManager.continueUploadTask(model: item)
                }
            }
            weakSelf.listTableView.reloadData()
            weakSelf.statusLabel.text = "正在同步（\(weakSelf.viewModel.dataSource.count)）..."
            weakSelf.hiddenWarningImageView(true)
            weakSelf.retryBtn.isHidden = true
        }.disposed(by: rx.disposeBag)
    }

    private func hiddenWarningImageView(_ isHidden: Bool) {
        if isHidden {
            warningImageView.snp.updateConstraints { make in
                make.left.equalTo(-14)
            }
            warningImageView.isHidden = true
        } else {
            warningImageView.snp.updateConstraints { make in
                make.left.equalTo(13)
            }
            warningImageView.isHidden = false
        }
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcUploadFailureVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return viewModel.dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcUploadFailureCell = tableView.dequeueReusableCell(withIdentifier: "WmcUploadFailureCell", for: indexPath) as! WmcUploadFailureCell
        let model = viewModel.dataSource[indexPath.row]
        cell.bindModel(model)

        cell.cancelTaskClosure = { task in

            let alert = WmcAlertView()
            alert.title = "提示"
            alert.msg = "取消后无法再次同步"
            alert.style = .custom(confirmTitle: "确定取消", cancelTitle: "再想想")
            alert.confirmBlock = { [weak self] in
                guard let weakSelf = self else { return }
                var index = -1
                for (i, item) in weakSelf.viewModel.dataSource.enumerated() {
                    if item.uuid == task.uuid {
                        index = i
                        break
                    }
                }
                WmcUploadQueueV2DBManager.delete(model: model) { isSuccess in
                    if isSuccess, index < weakSelf.viewModel.dataSource.count {
                        weakSelf.viewModel.dataSource.remove(at: index)
                    }
                    weakSelf.listTableView.reloadData()

                    if weakSelf.viewModel.dataSource.isEmpty {
                        weakSelf.tipView.isHidden = false
                    }

                    weakSelf.statusLabel.text = "同步失败（\(weakSelf.viewModel.dataSource.count)）"
                }
            }
            alert.show()
        }

        cell.retryTaskClosure = { [weak self] task in
            guard let weakSelf = self else { return }

            let networkType = YPNetworkReachability.queryNetworkReachabilityType()
            if networkType == .unknow || networkType == .notReachable {
                WmcHudManager.toast("网络不佳，请稍后再试")
                return
            }

            var uploadingCount = 0
            for (_, item) in weakSelf.viewModel.dataSource.enumerated() {
                if item.uuid == task.uuid {
                    item.uploading = true
                }
                if item.uploading {
                    uploadingCount += 1
                }
            }
            weakSelf.statusLabel.text = "正在同步（\(uploadingCount)）..."
            weakSelf.hiddenWarningImageView(true)
            weakSelf.retryBtn.isHidden = true
            weakSelf.listTableView.reloadData()
            WmcUploadQueueManager.continueUploadTask(model: model)
        }

        return cell
    }

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
        return 82
    }
}
